package indigo.net
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	import indigo.collections.ArrayList;
	import indigo.events.QueueEvent;
	import indigo.modules.ModuleInfo;
	
	[Event(name="ready",type="indigo.events.QueueEvent")]
	public class QueueLoader extends EventDispatcher
	{
		private var _modules:ArrayList;
		private var _currentIndex:int = 0;
		
		public function QueueLoader()
		{
					
		}

		public function load(modules:Array):void {
			if(!modules) throw new ArgumentError("Argument modules in load function is null");
		
			_currentIndex = 0;	
			_modules = new ArrayList(modules);
			loadInternal();
		}
		
		private function loadInternal():void {
			if(_currentIndex < _modules.count) {
				var context:LoaderContext = new LoaderContext(false,ApplicationDomain.currentDomain);
				var loader:Loader = new Loader();
				initDispatcher(loader.contentLoaderInfo);
				loader.load(new URLRequest(_modules[_currentIndex].moduleName),context);
			} else {
				// TODO: fin du chargement des modules et les stocker dans un gestionnaire pour une gestion utlérieur de la mémoire
				dispatchEvent(new QueueEvent(QueueEvent.READY));
			}
		}
		
		private function initDispatcher(dispatcher:IEventDispatcher):void {
			dispatcher.addEventListener(Event.COMPLETE,onModuleReady);
		}
		
		private function removeDispatcher(dispatcher:IEventDispatcher):void {
			dispatcher.removeEventListener(Event.COMPLETE,onModuleReady);
		}
		
		private function onModuleReady(e:Event):void {
			var loaderInfo:LoaderInfo = e.target as LoaderInfo;
			removeDispatcher(loaderInfo);
			ModuleInfo(_modules[_currentIndex++]).loader = loaderInfo.loader;
			
			loadInternal();
		}
	}
}